<template>
  <div class="wrapper">
    <div class="wap-content">
      <div class="query-wrapper">
        <div class="query-item">
          <div>搜索范围</div>
          <el-input
            v-model="goodsParams.keyword"
            placeholder="商品名称"
            icon="el-icon-search"
            clearable
            style="width: 150px"
            @on-clear="
              goodsData = [];
              goodsParams.keyword = '';
              goodsParams.current = 1;
              getQueryGoodsList();
            "
            @on-enter="
              () => {
                goodsData = [];
                goodsParams.current = 1;
                getQueryGoodsList();
              }
            "
          />
          <el-input
            v-model="goodsParams.goodsCode"
            placeholder="商品编号，多个商品编号以@隔开"
            icon="el-icon-search"
            clearable
            style="width: 260px"
            @on-clear="
              goodsData = [];
              goodsParams.goodsCode = '';
              goodsParams.current = 1;
              getQueryGoodsList();
            "
            @on-enter="
              () => {
                goodsData = [];
                goodsParams.goodsCode = '';
                goodsParams.current = 1;
                getQueryGoodsList();
              }
            "
          />
        </div>
        <div class="query-item">
          <el-cascader
            v-model="category"
            placeholder="请选择商品分类"
            clearable
            style="width: 180px"
            :options="skuList"
            @change="categoryChange"
          ></el-cascader>
        </div>
        <div class="query-item">
          <el-select
            v-model="brandId"
            placeholder="请选择品牌"
            filterable
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
        <div class="query-item">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="
              goodsData = [];
              refreshGoodsList();
            "
          >
            搜索
          </el-button>
        </div>
      </div>
      <div style="positon: retavle">
        <el-scrollbar
          ref="scrollbar"
          style="height: 400px"
        >
          <div class="wap-content-list flex-list">
            <div
              v-for="(item, index) in goodsData"
              :key="index"
              class="wap-content-item"
              :class="{ active: item.selected }"
              @click="checkedGoods(item, index)"
            >
              <div>
                <img
                  :src="item.small"
                  alt=""
                />
              </div>
              <div class="wap-content-desc">
                <div class="wap-content-desc-title">{{ item.goodsName }}</div>
                <div class="wap-sku">{{ item.simpleSpecs }}</div>
                <div class="wap-content-desc-bottom">
                  <div>
                    {{
                      isHomeDecorate || isDecorate
                        ? unitPrice(item.originalAmount, '￥')
                        : unitPrice(item.price, '￥')
                    }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="!complete"
            class="load-more"
          >
            <i class="el-icon-loading"></i>
            <span>加载中...</span>
          </div>
          <div
            v-if="empty"
            class="empty"
          >
            暂无商品信息
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>
<script>
import * as API_Goods from '@/api/items/goods';
import { unitPrice } from '@/filters';
import { getBrandListData, getCategoryTree } from '@/api/items/category';

export default {
  components: {},
  props: {
    selectedWay: {
      type: Array,
      default: () => [],
    },
    isDecorate: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      type: 'multiple', //单选或者多选 single  multiple
      isHomeDecorate: false,
      skuList: [], // 商品sku列表
      total: 0, // 商品总数
      goodsParams: {
        // 商品请求参数
        current: 1,
        size: 20,
        order: 'desc',
        keyword: '',
        sn: '',
        categoryId: '',
        marketEnable: 'UPPER',
        authFlag: 'PASS',
        brandId: '',
        goodsCode: '',
      },
      complete: false,
      category: [], // 分类
      goodsData: [], // 商品数据
      brandList: [], //品牌
      empty: false, // 空数据
      loading: false, // 加载状态
      brandId: '',
    };
  },
  computed: {
    _selectedWay: {
      get() {
        return this.selectedWay;
      },
      set(val) {
        this.$emit('selected', val);
        this.$emit('update:selectedWay', val);
      },
    },
  },
  watch: {
    brandId(val) {
      this.goodsParams.brandId = val;
    },
    'goodsParams.categoryId': {
      handler: function () {
        this.goodsData = [];
        this.goodsParams.current = 1;
        this.getQueryGoodsList();
      },
      deep: true,
    },
    'goodsParams.brandId': {
      handler: function () {
        this.goodsData = [];
        this.goodsParams.current = 1;
        this.getQueryGoodsList();
      },
      deep: true,
    },
  },
  mounted() {
    this.init();
    this.$refs.scrollbar.handleScroll = () => {
      var wrap = this.$refs.scrollbar.wrap;
      this.$refs.scrollbar.moveY = (wrap.scrollTop * 100) / wrap.clientHeight;
      this.$refs.scrollbar.moveX = (wrap.scrollLeft * 100) / wrap.clientWidth;
      const poor = wrap.scrollHeight - wrap.clientHeight;
      if (
        poor === parseInt(wrap.scrollTop) ||
        poor === Math.ceil(wrap.scrollTop) ||
        poor === Math.floor(wrap.scrollTop)
      ) {
        console.log('触底啦～～～～');
        this.handleReachBottom();
      }
    };
  },
  updated() {
    this.$refs.scrollbar.update();
  },
  methods: {
    unitPrice,
    categoryChange(val) {
      if (val && val.length) {
        this.goodsParams.categoryId = val.join(',');
      } else {
        this.goodsParams.categoryId = '';
      }
    },
    // 触底加载更多方法
    handleReachBottom() {
      setTimeout(() => {
        if (
          this.goodsParams.current * this.goodsParams.size ===
          this.goodsData.length
        ) {
          this.complete = false;
          this.goodsParams.current++;
          this.getQueryGoodsList();
        } else {
          this.complete = true;
        }
      }, 1500);
    },
    refreshGoodsList() {
      this.goodsParams.current = 1;
      this.complete = false;
      this.getQueryGoodsList();
    },

    // 获取商品列表
    async getQueryGoodsList() {
      try {
        this.loading = true;
        if (this.isHomeDecorate || this.isDecorate) {
          const res = await API_Goods.getGoodsEsData(this.goodsParams);
          this.initGoods(res);
        } else {
          this.goodsParams.sort = 'desc';
          const res = await API_Goods.getGoodsSkuData(this.goodsParams);
          this.initGoods(res);
        }
      } catch (error) {
        this.loading = false;
        throw new Error(error);
      }
    },
    // 获取列表方法
    initGoods(res) {
      console.log('res = ', res);
      if (res.data.data.records.length !== 0) {
        this.empty = false;
        this.complete = true;
        res.data.data.records.forEach((item) => {
          item.selected = false;
          if (this.isHomeDecorate || this.isDecorate) {
            item.id = item.skuId;
          }
          item.___type = 'goods'; //设置为goods让pc wap知道标识
          this._selectedWay.forEach((e) => {
            if (e.id && e.id === item.id) {
              item.selected = true;
            }
          });
        });
        /**
         * 解决数据请求中，滚动栏会一直上下跳动
         */
        // this.total = res.data.data.total;
        this.goodsData.push(...res.data.data.records);
      } else {
        this.complete = true;
        this.empty = true;
      }
      this.loading = false;
    },
    // 查询商品
    init() {
      var timer = setInterval(() => {
        this.getQueryGoodsList();
        clearInterval(timer);
      }, 120);

      // API_Goods.getGoodsSkuData(this.goodsParams).then((res) => {
      //   // 商品
      //   this.initGoods(res);
      // });
      getCategoryTree().then((res) => {
        this.deepGroup(res.data.data);
      });
      getBrandListData().then((res) => {
        this.brandList = res.data.data;
      });
      // if (localStorage.getItem('category')) {
      //   this.deepGroup(JSON.parse(localStorage.getItem('category')))
      // } else {
      //   setTimeout(() => {
      //     this.deepGroup(JSON.parse(localStorage.getItem('category')))
      //   },3000)
      // }
    },

    deepGroup(val) {
      if (val) {
        val.forEach((item) => {
          const childWay = []; //第二级
          // 第二层
          if (item.children) {
            item.children.forEach((child) => {
              // // 第三层
              if (child.children) {
                child.children.forEach((grandson, index, arr) => {
                  if (grandson.children) {
                    grandson.children.forEach(
                      (fourth, fourthIndex, fourthArr) => {
                        fourthArr[fourthIndex] = {
                          value: fourth.id,
                          label: fourth.name,
                          children: '',
                        };
                      }
                    );
                  }

                  arr[index] = {
                    value: grandson.id,
                    label: grandson.name,
                    children: grandson.children,
                  };
                });
              }
              const children = {
                value: child.id,
                label: child.name,
                children: child.children,
              };
              childWay.push(children);
            });
          }
          // 第一层
          const way = {
            value: item.id,
            label: item.name,
            children: childWay,
          };

          this.skuList.push(way);
        });
      }
    },

    /**
     * 点击商品
     */
    checkedGoods(val, index) {
      // 如果单选的话
      if (this.type !== 'multiple') {
        this.goodsData.forEach((item) => {
          item.selected = false;
        });
        this._selectedWay = [val];
        val.selected = true;

        return false;
      }

      if (val.selected === false) {
        val.selected = true;
        this._selectedWay.push(val);
      } else {
        val.selected = false;
        for (let i = 0; i < this._selectedWay.length; i++) {
          if (this._selectedWay[i].id === val.id) {
            this._selectedWay.splice(i, 1);
            break;
          }
        }
      }
    },
  },
};
</script>
<style scoped lang="scss">
@import './style.scss';
.load-more {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}
.wap-content {
  width: 100%;
}

.empty {
  text-align: center;
  padding: 8px 0;
  width: 100%;
}

.wap-content {
  flex: 1;
  padding: 0;
}

.wap-content-list {
  position: relative;

  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

.wap-content-item {
  width: 210px;
  margin: 10px 7px;
  padding: 6px 0;
}

// .wap-content-item{

// }
.active {
  background: url('../../assets/selected.png') no-repeat;
  background-position: right;
  background-size: 10%;
}
</style>
